package onehito.controller.comunication;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.channels.Channel;
import java.util.HashMap;
import java.util.Map;

import net.arnx.jsonic.JSON;
import onehito.model.Chat;
import onehito.service.ComunicationService;
import onehito.util.RequestAction;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.RequestMap;
import org.slim3.util.ThrowableUtil;

import com.google.appengine.api.channel.ChannelFailureException;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

public class ChatsController extends Controller {

    ComunicationService cService = new ComunicationService();

    @Override
    public Navigation run() throws Exception {

        String action = request.getParameter("action");
        System.out.println("action : " + action);
        Map<String, Object> data = new HashMap<String, Object>();
        if (action != null) {
            switch (action) {
            case RequestAction.ADD_MSG:
                // add new node
                Chat chat = cService.add(new RequestMap(request));
                data.put("chat", chat);
                this.json(data);
                break;
            default:
                break;
            }
        }
        return null;
    }

    private void json(Object data) {
        String encoding = request.getCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }
        response.setContentType("application/json; charset=" + encoding);
        try {
            PrintWriter out = null;
            try {
                out =
                    new PrintWriter(new OutputStreamWriter(
                        response.getOutputStream(),
                        encoding));
                out.print(JSON.encode(data));
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (IOException e) {
            ThrowableUtil.wrapAndThrow(e);
        }
    }
}
